/**
 * 
 */
package com.hw.hcit.feature;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import com.hw.hcit.R;
import com.hw.hcit.conf.Config;
import com.hw.hcit.conf.JCtrlCallback;
import com.hw.hcit.conf.JTestItem;
import android.media.AudioSystem;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.NoCopySpan.Concrete;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

/**
 * @author gaoshengpan
 *
 */
public class AuxiliaryMicLoopbackTestItem extends JTestItem {
    private TextView textView1, textView2;
    private Button mButton;
    private boolean inRecord = false;
    private boolean started = false;
    private MediaRecorder mMediaRecorder;
    private Context mContext;
    private AudioManager mAudioManager;
    private String mAudiofilePath;
    private boolean isRecording = false;
    private String TAG = "AuxiliaryMicLoopbackTestItem";
    private boolean tested = false;
    private boolean powerClicked = false;
    private Button mButton1, mButton2;
    private static MediaPlayer mMediaPlayer;

    /**
     * @param cb
     */
    public AuxiliaryMicLoopbackTestItem(JCtrlCallback cb) {
        super(cb);
        // TODO Auto-generated constructor stub
    }

    /**
     * 
     */
    public AuxiliaryMicLoopbackTestItem() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        mContext = Config.GetActivity();
        mAudioManager = (AudioManager) mContext
                .getSystemService(Context.AUDIO_SERVICE);
        /*
         * IntentFilter filter = new IntentFilter();
         * filter.addAction(Intent.ACTION_HEADSET_PLUG);
         * mContext.registerReceiver(mBReceiver, filter);
         */
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        // TODO Auto-generated method stub
        View rootView = inflater.inflate(R.layout.auxiliarymicloopbacktest,
                container, false);
        textView1 = (TextView) rootView.findViewById(R.id.textView1);
        textView2 = (TextView) rootView.findViewById(R.id.textView2);
        mButton = (Button) rootView.findViewById(R.id.button1);
        mButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!started) {
                    Log.d(TAG, "onClick------------>onClick0");
                    started = true;
                    textView1.setText(getString(R.string.recording));
                    mButton.setText(getString(R.string.toplay));
                    mButton.setEnabled(false);
                    inRecord();
                } else {
                    if (mButton.getText() == getString(R.string.toplay)) {
                        Log.d(TAG, "onClick------------>onClick1");
                        // in play
                        textView1.setText(getString(R.string.playing));
                        mButton.setText(getString(R.string.torecord));
                        mButton.setEnabled(false);
                        inPlay();

                    } else {
                        // in record
                        Log.d(TAG, "onClick------------>onClick2");

                        textView1.setText(getString(R.string.recording));
                        mButton.setText(getString(R.string.toplay));
                        mButton.setEnabled(false);
                        inRecord();

                    }
                }
            }
        });
        mButton1 = (Button) rootView.findViewById(R.id.button2);
        mButton2 = (Button) rootView.findViewById(R.id.button3);
        mButton1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if (Config.CURR_PROJECT.isAuto()) {
                    if (!Config.ageingTested) {
                        rewriteOneByteOfNv2499(17, 'P');
                    } else {
                        rewriteOneByteOfNv2499(48, 'P');
                    }
                }
                testFinish(true, 1, true);

            }
        });
        mButton2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if (Config.CURR_PROJECT.isAuto()) {
                    if (!Config.ageingTested) {
                        rewriteOneByteOfNv2499(17, 'F');
                    } else {
                        rewriteOneByteOfNv2499(48, 'F');
                    }
                }
                testFinish(false, 1, false);

            }
        });
        return rootView;

    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        AudioSystem.setForceUse(AudioSystem.FOR_RECORD,
                AudioSystem.FORCE_SPEAKER);
        /*15-12-24 gaoshenpan fix open mic to protect Running Crash&&closeMic begin */
        mAudioManager.setMicrophoneMute(false);
        /*15-12-24 gaoshenpan fix open mic to protect Running Crash&&closeMic end */
        Log.d(TAG, "onResume()");
        /* 15-10-20 gaoshenpan fix create mMediaRecorder&mMediaPlayer begin */
        if (mMediaRecorder == null) {
            Log.d(TAG, "onResume()-----mMediaRecorder == null");
            mMediaRecorder = new MediaRecorder("com.hw.hcit");
        } else {
            Log.d(TAG, "onResume()-----mMediaRecorder != null");
        }

        if (mMediaPlayer == null) {
            Log.d(TAG, "onResume()-----mMediaPlayer == null");
            mMediaPlayer = new MediaPlayer();
        } else {
            Log.d(TAG, "onResume()-----mMediaPlayer != null");
        }
        /* 15-10-20 gaoshenpan fix create mMediaRecorder&mMediaPlayer end */
        mButton.setEnabled(true);
        mButton1.setEnabled(false);
        mButton2.setEnabled(false);

        tested = false;
        powerClicked = false;
        inRecord = false;
        /* gaoshenpan 15-09-14 modify string begin */
        textView1.setText(getString(R.string.mic_loop_test));
        /* gaoshenpan 15-09-14 modify string end */
        mButton.setText(getString(R.string.torecord));
    }

    /*
     * 15-10-20 gaoshenpan deal with mMediaRecorder&mMediaPlayer
     * onPause&onStop&onDestroy begin
     */
    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        AudioSystem.setForceUse(AudioSystem.FOR_RECORD, AudioSystem.FORCE_NONE);
        Log.d(TAG, "onPause()");
        if (isRecording && mMediaRecorder != null) {
            mMediaRecorder.stop();
            mMediaRecorder.release();
            mMediaRecorder = null;
            mHandler.removeMessages(0);
            Log.d(TAG, "------onPause----1-----");
        }
        if (mMediaPlayer == null) {
            Log.d(TAG, "------onPause----mMediaPlayer-----null");
        }
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
            Log.d(TAG, "------onPause----mMediaPlayerstop-----");
            mMediaPlayer.release();
            mMediaPlayer = null;
            Log.d(TAG, "------onPause----mMediaPlayerRelease-----");
        }
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        Log.d(TAG, "onStop()");
        if (isRecording && mMediaRecorder != null) {
            mMediaRecorder.stop();
            mMediaRecorder.release();
            mMediaRecorder = null;
            Log.d(TAG, "------onStop----1-----");
        }

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Log.d(TAG, "onDestroy()");
        if (mMediaRecorder != null) {
            mMediaRecorder.release();
            mMediaRecorder = null;
            Log.d(TAG, "------onDestroy----1-----");
        }
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            Log.d(TAG, "------onDestroy----mMediaPlayerstop-----");
            mMediaPlayer.release();
            mMediaPlayer = null;
            Log.d(TAG, "------onDestroy----mMediaPlayerRelease-----");
        }
    }

    /*
     * 15-10-20 gaoshenpan deal with mMediaRecorder&mMediaPlayer
     * onPause&onStop&onDestroy end
     */

    public void inRecord() {

        try {

            // textView1.setText(getString(R.string.recording));
            if (Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED)) {
                Log.d(TAG, "Environment.getExternalStorageState()------------>"
                        + Environment.getExternalStorageState());
            }
            record();
            isRecording = true;

            mHandler.sendEmptyMessageDelayed(0, 2500);
        } catch (Exception e) {
            loge(e);
        }
    }

    public void inPlay() {
        mButton.setEnabled(false);
        mButton.setText(getString(R.string.torecord));
        try {
            replay();

        } catch (Exception e) {
            loge(e);
        }

    }

    void record() throws IllegalStateException, IOException,
            InterruptedException {
        if (mMediaRecorder != null) {
            Log.d(TAG, "------------>mMediaRecorder!=null");
            mMediaRecorder.reset();
        } else {
            mMediaRecorder = new MediaRecorder("com.hw.hcit");
        }
        mButton1.setEnabled(false);
        mButton2.setEnabled(false);
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mMediaRecorder.setOnErrorListener(new MediaRecorder.OnErrorListener() {
            @Override
            public void onError(MediaRecorder mediarecorder, int arg1, int arg2) {
                // TODO Auto-generated method stub
                Log.d(TAG, "------->" + "mMediaRecorder===onError");
                if (mediarecorder != null && isRecording) {
                    Log.d(TAG, "------->" + "mMediaRecorder===xxxxxxx");
                    mediarecorder.stop();
                    mediarecorder.release();
                    mediarecorder = null;
                }
            }
        });
        // Environment.setUserRequired(false);
        mMediaRecorder.setOutputFile("storage/sdcard0/"
                + "/testHeadset.amr");
        mAudiofilePath = "storage/sdcard0/" + "/testHeadset.amr";
        Log.d(TAG, "path------------>"
                + Environment.getExternalStorageDirectory().toString());
        mMediaRecorder.prepare();
        mMediaRecorder.start();
    }

    void replay() throws IllegalArgumentException, IllegalStateException,
            IOException {
        textView1.setText(getString(R.string.playing));
        mButton.setEnabled(false);
        File file = new File(mAudiofilePath);
        FileInputStream mFileInputStream = new FileInputStream(file);
        /* 15-09-24 gaoshenpan fix can not play begin */
        /* 15-10-20 gaoshenpan fix mMediaPlayernot play begin */
        if (mMediaPlayer != null) {
            mMediaPlayer.reset();
            Log.d(TAG, "replay()-----mMediaPlayer != null");
        } else {
            mMediaPlayer = new MediaPlayer();
            Log.d(TAG, "replay()-----mMediaPlayer == null");
        }

        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer player, int arg1, int arg2) {
                // TODO Auto-generated method stub
                if (player != null && player.isPlaying()) {
                    Log.d(TAG, "------->" + "onError====mMediaPlayer");
                    player.stop();
                    Log.d(TAG, "------->" + "onError====mMediaPlayer---stop()");
                    player.release();
                    Log.d(TAG, "------->"
                            + "onError====mMediaPlayer---release()");
                    player = null;
                    Log.d(TAG, "------->"
                            + "onError====mMediaPlayer---release()");
                }
                Log.d(TAG, "------->" + "onError");
                return false;
            }
        });
        /* 15-09-24 gaoshenpan fix can not play end */
        mMediaPlayer.setDataSource(mFileInputStream.getFD());
        mMediaPlayer.prepare();
        mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                Log.d(TAG, "------->" + "onPrepared");
                mp.start();
                Log.d(TAG, "------->" + "onPrepared1");
            }
        });

        mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mPlayer) {

                Log.d(TAG, "------->" + "onCompletion");
                Log.d(TAG, "------->" + "onCompletion===1111111");
                mPlayer.stop();
                Log.d(TAG, "------->" + "onCompletion===stop()");
                File file = new File(mAudiofilePath);
                file.delete();
                mHandler.sendEmptyMessage(1);

            }
        });
        /* 15-10-20 gaoshenpan fix mMediaPlayernot play end */

    }

    private void loge(Object e) {

        if (e == null)
            return;
        Thread mThread = Thread.currentThread();
        StackTraceElement[] mStackTrace = mThread.getStackTrace();
        String mMethodName = mStackTrace[3].getMethodName();
        e = "[" + mMethodName + "] " + e;
        Log.e(TAG, e + "");
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            /*
             * if(!mAudioManager.isWiredHeadsetOn()){
             * showWarningDialog(getString(R.string.insertheadset)); }
             */
            Log.d(TAG, "mhandle------------>");
            switch (msg.what) {

            case 0:
                if (isRecording && mMediaRecorder != null) {
                    Log.d(TAG, "mhandle------------>recorded");
                    mMediaRecorder.stop();

                    isRecording = false;
                    mButton.setEnabled(true);
                    textView1.setText(getString(R.string.recorded));
                    /*
                     * try { replay(); } catch (Exception e) { Log.e(TAG,
                     * "Exception e------>"+e.toString()); }
                     */
                }
                break;
            /*
             * case 1: textView1.setText(getString(R.string.recorded));
             * mButton.setEnabled(true); break;
             */
            case 1:
                Log.d(TAG, "mhandle------------>played");
                textView1.setText(getString(R.string.played));
                tested = true;
                mButton1.setEnabled(true);
                mButton2.setEnabled(true);
                mButton.setEnabled(true);
                break;
            default:
                break;
            }
        }
    };

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        return true;
    }
    /*
     * @Override public boolean dispatchKeyEvent(KeyEvent event) { // TODO
     * Auto-generated method stub if (event.getKeyCode() ==
     * KeyEvent.KEYCODE_VOLUME_DOWN) { dissmissPowerClicked(); Log.d(TAG,
     * " --------->KeyEvent.KEYCODE_VOLUME_DOWN"); if (powerClicked) {
     * Log.d(TAG, "powerClicked --------->KeyEvent.KEYCODE_VOLUME_DOWN");
     * testFinish(false, 1, false); return true; } if (tested) { Log.d(TAG,
     * "tested --------->KeyEvent.KEYCODE_VOLUME_DOWN"); testFinish(true, 1,
     * true); } else { Log.d(TAG, " --------->showTestUncomplete");
     * showTestUncomplete(); } } else if (event.getKeyCode() ==
     * KeyEvent.KEYCODE_VOLUME_UP) { dissmissPowerClicked(); testFinish(true,
     * -1, true); } else if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
     * Log.d(TAG, "powerClicked --------->KeyEvent.KEYCODE_POWER"); powerClicked
     * = true; showPowerClicked(); } return true; }
     */

}
